import 'package:flutter/material.dart';
import '../../models/chat.dart';
import '../home/widgets/chat_tile.dart';
import '../chat/chat_detail_page.dart';

class SearchPage extends SearchDelegate<String> {
  final List<Chat> chats;

  SearchPage(this.chats);

  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, '');
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return _buildSearchResults(context);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return _buildSearchResults(context);
  }

  Widget _buildSearchResults(BuildContext context) {
    final results = chats.where((chat) {
      return chat.name.toLowerCase().contains(query.toLowerCase()) ||
          chat.message.toLowerCase().contains(query.toLowerCase());
    }).toList();

    return ListView.builder(
      itemCount: results.length,
      itemBuilder: (context, index) {
        final chat = results[index];
        return ChatTile(
          chat: chat,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ChatDetailPage(chat: chat),
              ),
            );
          },
        );
      },
    );
  }
}
